package kr.hkit.android_bookmgr.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DTO.BookBoard;
import kr.hkit.android_bookmgr.adapter.BoardListAdapter;
import kr.hkit.android_bookmgr.parser.BoardParser;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BookBoardActivity extends Activity {

	private EditText writerEdit, commentEdit ;
	private TextView writedateText;
	private String board_writer, board_comment, board_writedate;
	private ArrayList<BookBoard> boardList;
	private ProgressDialog dialog;
	private int mYear, mMonth, mDay;
	private ListView listview;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.bookboard_activity);
		Log.d("BOARD", "BOARD - onCreate");
		
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);
		
		//게시글 리스트 불러오기 - resume에서 불러옴 
		//getNewList();
		
		calendar();
		 
		listview = (ListView) findViewById(R.id.bookboard_list);
		listview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			
				final int pos = position;
				
				new AlertDialog.Builder(BookBoardActivity.this).
				setTitle("선택하시오").
				setItems(R.array.booklist_updel, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						final int whichone = which; //수정이냐 삭제냐 
						
						if(which==0){ //수정
							
							final LinearLayout linear = (LinearLayout) View.inflate(BookBoardActivity.this, R.layout.bookboard_dialog, null);
							writerEdit = (EditText) linear.findViewById(R.id.bookboard_dia_bookwriter);
							writerEdit.setText(boardList.get(pos).getBoard_writer());
							commentEdit = (EditText) linear.findViewById(R.id.bookboard_dia_bookcomm);
							commentEdit.setText(boardList.get(pos).getBoard_comment());
							writedateText = (TextView) linear.findViewById(R.id.bookboard_dia_writedate);
							writedateText.setText(boardList.get(pos).getBoard_writedate());
							
							
							new AlertDialog.Builder(BookBoardActivity.this) //수정
							.setTitle("수정하기")
							.setView(linear)
							.setPositiveButton("확인",
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int whichButton) {
											
											Intent intent = new Intent(BookBoardActivity.this,BookBoardWebViewActivity.class);
											intent.putExtra("whichone", whichone); //수정이냐 삭제냐
											intent.putExtra("board_id_update", boardList.get(pos).board_id); //id 구하기
											intent.putExtra("board_writer_update", writerEdit.getText().toString());
											intent.putExtra("board_comment_update", commentEdit.getText().toString());
											intent.putExtra("board_writedate_update", writedateText.getText().toString());
											startActivity(intent);
											//Toast.makeText(BookBoardActivity.this, boardList.get(pos).board_id +" "+commentEdit.getText().toString(),Toast.LENGTH_LONG).show();
											
										}
									})
							.setNegativeButton("취소",new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int whichButton) {
											Toast.makeText(BookBoardActivity.this,"취소하였습니다", Toast.LENGTH_SHORT).show();
										}
									}).show();
						
						}else{ // 삭제 확인창 띄우기 
							new AlertDialog.Builder(BookBoardActivity.this)
							.setMessage("삭제하시겠습니까?") //OK
							.setPositiveButton("확인", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) { //확인버튼 클릭시 삭제
									
									Intent intent = new Intent(BookBoardActivity.this,BookBoardWebViewActivity.class);
									intent.putExtra("whichone", whichone); //수정이냐 삭제냐
									intent.putExtra("board_id_del", boardList.get(pos).board_id); //id 구하기
									startActivity(intent);
									
									Toast.makeText(getBaseContext(),"삭제되었습니다.", Toast.LENGTH_SHORT).show();
								}
							})
							.setNegativeButton("취소", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									Toast.makeText(getBaseContext(),"취소하였습니다.", Toast.LENGTH_SHORT).show();
								}
							})
							.show();
							//삭제확인 AlertDialog
						}//if~else
					}//onClick 수정, 삭제 대화상자
				})
				.setNegativeButton("취소", null)
				.show();
				
				return true;
				
			}//onItemLongClick
		});//setOnItemLongClickListener

	}//onCreate
	
	
	 public boolean onOptionsItemSelected(android.view.MenuItem item) {
			switch (item.getItemId()) {
				case android.R.id.home:
					  Intent intent = new Intent(this, BookListActivity.class); 
					  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //액티비티 쌓이지 않기위해. 바로메인
					  startActivity(intent);
					  break;
			}
			return super.onOptionsItemSelected(item);

		}; //홈으로 이동
		
		
	private void calendar(){
		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
	}
	
	
	public void mOnClick(View v) { //글 등록 
		switch (v.getId()) {
		case R.id.bookboard_btnadd:
			final LinearLayout linear = (LinearLayout) View.inflate(BookBoardActivity.this, R.layout.bookboard_dialog, null);

			writedateText = (TextView) linear.findViewById(R.id.bookboard_dia_writedate);
			writedateText.setText(String.format("%d/%02d/%d", mYear, mMonth + 1,mDay));
			//writedateEdit.setOnFocusChangeListener(mOnFocusChangeListener);

			writerEdit = (EditText) linear.findViewById(R.id.bookboard_dia_bookwriter);
			commentEdit = (EditText) linear.findViewById(R.id.bookboard_dia_bookcomm);

			new AlertDialog.Builder(BookBoardActivity.this)
					.setTitle("글쓰기")
					.setView(linear)
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int whichButton) {
									// DB인서트! OK

									board_writer = writerEdit.getText().toString();
									board_comment = commentEdit.getText().toString();
									board_writedate = writedateText.getText().toString();

									Intent intent = new Intent(BookBoardActivity.this,BookBoardWebViewActivity.class);
									intent.putExtra("board_writer", board_writer);
									intent.putExtra("board_comment", board_comment);
									intent.putExtra("board_writedate", board_writedate);
									startActivity(intent);

									//Toast.makeText(BookBoardActivity.this, board_writer + "" + board_comment + ""+ board_writedate,Toast.LENGTH_LONG).show();
									
								}
							})
					.setNegativeButton("취소",new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int whichButton) {
									Toast.makeText(BookBoardActivity.this,"취소하였습니다", Toast.LENGTH_SHORT).show();
								}
							}).show();
			break;
			
		case R.id.bookboard_refresh:
			
			getNewList();
			
		}
	}// mOnClick

	@SuppressLint("HandlerLeak")
	private final Handler handler = new Handler(){
		public void handleMessage(final Message msg){
    		dialog.dismiss();
    		
    		BoardListAdapter adapter = new BoardListAdapter(BookBoardActivity.this, R.layout.bookboard_list_row, boardList);
    		listview.setAdapter(adapter);
    		
    	}
    };
	
	
	 public void getNewList(){
			dialog=ProgressDialog.show(this, "Loading..", "리스트를 불러옵니다",true,false);
			new Thread(){
				public void run(){
					
					boardList = BoardParser.getData(); // 네이버 api를 이용해 정보를 얻어옴
					handler.sendEmptyMessage(0);
				}
			}.start();
		}//getNewList

	 
	 @Override
		protected void onResume() {
			Log.d("BOARD", "BOARD - onResume");
			super.onResume();
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			getNewList();
		}
	 
	/* 
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		Log.d("BOARD", "BOARD - onPostCreate");
		// TODO Auto-generated method stub
		super.onPostCreate(savedInstanceState);
	}


	@Override
	protected void onStart() {
		Log.d("BOARD", "BOARD - onStart");
		// TODO Auto-generated method stub
		super.onStart();
	}


	@Override
	protected void onRestart() {
		Log.d("BOARD", "BOARD - onRestart");
		// TODO Auto-generated method stub
		super.onRestart();
	}


	


	@Override
	protected void onPostResume() {
		Log.d("BOARD", "BOARD - onPostResume");
		// TODO Auto-generated method stub
		super.onPostResume();
	}


	@Override
	protected void onPause() {
		Log.d("BOARD", "BOARD - onPause");
		// TODO Auto-generated method stub
		super.onPause();
	}


	@Override
	protected void onStop() {
		Log.d("BOARD", "BOARD - onStop");
		// TODO Auto-generated method stub
		super.onStop();
	}


	@Override
	protected void onDestroy() {
		Log.d("BOARD", "BOARD - onDestroy");
		// TODO Auto-generated method stub
		super.onDestroy();
	}*/
	 
}//end of class


